package plug_in_javafx_dt.launching;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;

public class JFXClasspathContainer implements IClasspathContainer{
	
	private IPath path;
	private IJavaProject project;
	 
	private final String ROOT_DIR = "Plug-in JavaFX DT";
	private HashSet<String> _exts;
	private String _desc;
	private File _dir;
	
	public JFXClasspathContainer(IPath path, IJavaProject project) {
		this.path = path;
		this.project = project;
		
		 // extract the extension types for this container from the path
	    String extString = path.lastSegment();
	    _exts = new HashSet<String>();
	    String[] extArray = extString.split(",");
	    for(String ext: extArray) {
	        _exts.add(ext.toLowerCase());
	    }
	    // extract the directory string from the PATH and create the directory relative 
	    // to the project
	    path = path.removeLastSegments(1).removeFirstSegments(1);   
	    File rootProj = project.getProject().getLocation().makeAbsolute().toFile(); 
	    if(path.segmentCount()==1 && path.segment(0).equals(ROOT_DIR)) {
	        _dir = rootProj;
	        path = path.removeFirstSegments(1);
	    } else {
	        _dir = new File(rootProj, path.toString());
	    }        
	        
	    // Create UI String for this container that reflects the directory being used
	    _desc = "/" + path + " Libraries";
	}

	private FilenameFilter _dirFilter = new FilenameFilter() {
	      
	    /** 
	     * This File filter is used to filter files that are not in the configured 
	     * extension set.  Also, filters out files that have the correct extension 
	     * but end in -src, since filenames with this pattern will be attached as 
	     * source.   
	     * 
	     * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
	     */
	    public boolean accept(File dir, String name) {
	        // lets avoid including filenames that end with -src since 
	        // we will use this as the convention for attaching source
	        String[] nameSegs = name.split("[.]");
	        if(nameSegs.length != 2) {
	            return false;
	        }
	        if(nameSegs[0].endsWith("-src")) {
	            return false;
	        }            
	        if(_exts.contains(nameSegs[1].toLowerCase())) {
	            return true;
	        }           
	        return false;
	    }
	};
	
	
	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int getKind() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public IPath getPath() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	/** 
	 * Returns a set of CPE_LIBRARY entries from the configured project directory 
	 * that conform to the configured set of file extensions and attaches a source 
	 * archive to the libraries entries if a file with same name ending with 
	 * -src is found in the directory. 
	 * 
	 * @see org.eclipse.jdt.core.IClasspathContainer#getClasspathEntries()
	 */
	public IClasspathEntry[] getClasspathEntries() {
	    ArrayList<IClasspathEntry> entryList = new ArrayList<IClasspathEntry>();
	    // fetch the names of all files that match our filter
	    File[] libs = _dir.listFiles(_dirFilter);
	    for( File lib: libs ) {
	        // strip off the file extension
	        String ext = lib.getName().split("[.]")[1]; 
	        // now see if this archive has an associated src jar
	        File srcArc = new File(lib.getAbsolutePath().replace("."+ext, "-src."+ext));
	        Path srcPath = null;
	        // if the source archive exists then get the path to attach it
	        if( srcArc.exists()) {
	            srcPath = new Path(srcArc.getAbsolutePath());
	        }
	        // create a new CPE_LIBRARY type of cp entry with an attached source 
	        // archive if it exists
	        entryList.add( JavaCore.newLibraryEntry(
	        new Path(lib.getAbsolutePath()) , srcPath, new Path("/")));                
	    }
	    // convert the list to an array and return it
	    IClasspathEntry[] entryArray = new IClasspathEntry[entryList.size()];
	    return (IClasspathEntry[])entryList.toArray(entryArray);
	}
}
